package com.example.sanguogameserver.service;

import com.baomidou.mybatisplus.extension.service.IService;
import com.example.sanguogameserver.entity.PlayerItem;
import com.example.sanguogameserver.mapper.PlayerItemMapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.sanguogameserver.response.PlayerItemResp;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 玩家道具 服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2024-03-18
 */
@Service
public class PlayerItemService extends ServiceImpl<PlayerItemMapper, PlayerItem> implements IService<PlayerItem> {

    public List<PlayerItemResp> listAllByPlayerId(Integer playerId) {
        return lambdaQuery()
                .eq(PlayerItem::getPlayerId, playerId)
                .list()
                .stream()
                .map(item -> {
                    PlayerItemResp playerItemResp = new PlayerItemResp();
                    BeanUtils.copyProperties(item, playerItemResp);
                    return playerItemResp;
                }).collect(Collectors.toList());
    }


    public void savePlayerItemBatch(List<PlayerItem> playerItems) {
        for (PlayerItem playerItem : playerItems) {
            savePlayerItem(playerItem);
        }
    }

    public void savePlayerItem(PlayerItem playerItem) {
        PlayerItem oldPlayerItem = getByPlayerIdAndItemId(playerItem.getPlayerId(), playerItem.getItemId());
        if (oldPlayerItem != null) {
            playerItem.setId(oldPlayerItem.getId());
            Integer newItemCount = playerItem.getItemCount()+oldPlayerItem.getItemCount();
            playerItem.setItemCount(newItemCount);
        }
        saveOrUpdate(playerItem);
    }

    public PlayerItem getByPlayerIdAndItemId(Integer playerId, Integer itemId) {
        return lambdaQuery()
                .eq(PlayerItem::getPlayerId, playerId)
                .eq(PlayerItem::getItemId, itemId)
                .last("limit 1")
                .one();
    }


}
